﻿using System.Net.Http.Json;
using Test.Mvc.Models;
namespace Test.Mvc.Services
{
    public class TestWeatherService
    {
        private readonly HttpClient _httpClient;

        public TestWeatherService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        // 直接调用 Open-Meteo 7 天预报 API
        // 文档: https://open-meteo.com/
        public async Task<List<WeatherForecast>> GetForecastAsync(double latitude, double longitude)
        {
            var url = $"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&daily=weathercode,temperature_2m_max&timezone=auto";
            var response = await _httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();

            var json = await response.Content.ReadFromJsonAsync<OpenMeteoDailyResponse>();
            var forecasts = new List<WeatherForecast>();
            if (json?.daily?.time == null || json.daily.temperature_2m_max == null || json.daily.weathercode == null)
            {
                return forecasts;
            }

            for (int i = 0; i < json.daily.time.Length; i++)
            {
                if (!DateTime.TryParse(json.daily.time[i], out var date))
                {
                    continue;
                }
                var temp = i < json.daily.temperature_2m_max.Length ? json.daily.temperature_2m_max[i] : (double?)null;
                var code = i < json.daily.weathercode.Length ? json.daily.weathercode[i] : (int?)null;
                forecasts.Add(new WeatherForecast
                {
                    Date = date,
                    Temperature = temp ?? 0,
                    Weather = MapWeatherCode(code)
                });
            }

            return forecasts;
        }

        private static string MapWeatherCode(int? code)
        {
            return code switch
            {
                0 => "晴",
                1 or 2 or 3 => "多云",
                45 or 48 => "雾",
                51 or 53 or 55 => "毛毛雨",
                61 or 63 or 65 => "小到大雨",
                71 or 73 or 75 => "小到大雪",
                80 or 81 or 82 => "阵雨",
                95 => "雷阵雨",
                96 or 99 => "雷阵雨伴冰雹",
                _ => "未知",
            };
        }

        // 强类型响应映射
        public class OpenMeteoDailyResponse
        {
            public DailyData daily { get; set; }
        }

        public class DailyData
        {
            public string[] time { get; set; }
            public double[] temperature_2m_max { get; set; }
            public int[] weathercode { get; set; }
        }
    }
}
